#include "commonlooper.h"
#include"dlog.h"

CommonLooper::CommonLooper():_request_abort(false), _running(false)
{

}

CommonLooper::~CommonLooper()
{
    stop();
}

RET_CODE CommonLooper::start()
{
    LogInfo("into");
    // 创建线程同时执行任务
    _worker = new std::thread(trampoline, this);
    if(!_worker)
    {
        LogError("new thread failed");
        return RET_FAIL;
    }
    return RET_OK;
}

void CommonLooper::stop()
{
    // 标记现在需要停止线程了
    _request_abort = true;
    // 如果线程还未被销毁
    if(_worker)
    {
        // 等待线程执行完毕
        _worker->join();
        delete _worker;
        _worker = NULL;
    }
}

bool CommonLooper::running()
{
    return _running;
}

void CommonLooper::setRunning(bool running)
{
    _running = running;
}

void *CommonLooper::trampoline(void *p)
{
    LogInfo("into");
    ((CommonLooper*)p)->setRunning(true);//标记线程开始运行
    ((CommonLooper*)p)->loop(); // 执行任务，一般来说这是个while循环
    ((CommonLooper*)p)->setRunning(false);//标记线程运行结束
    LogInfo("leave");
    return NULL;
}
